package com.icehand.utils.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;

/**
 * create by icehand on 2017年8月25日 11:48:32
 */
public class RedisCacheUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(RedisCacheUtils.class.getName());

	private static final int DEFAULT_CACHE_EXPIRE_SECS = 600;

	private static JedisPool jedisPool;
	private static Jedis jedis;

	public RedisCacheUtils(){}

	public static Jedis getJedis(){
		try {
			jedisPool = JedisFactory.getInstance().getJedisPool();
		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
		}
		jedis = jedisPool.getResource();
		return jedis;
	}

	public static void returnJedis(){
		jedis.close();
	}

	public static void put(String cacheKey, String value, int expireInSecs) {
		Jedis jedis = getJedis();
		jedis.set(cacheKey, value);
		if (expireInSecs > 0)
			jedis.expire(cacheKey, expireInSecs);
		returnJedis();
	}

	public static void put(String cacheKey, String value){
		put(cacheKey,value,DEFAULT_CACHE_EXPIRE_SECS);
	}

	public static String get(String cacheKey) {
		String cache =  getJedis().get(cacheKey);
		returnJedis();
		return cache;
	}

	public static void del(String cacheKey) {
		getJedis().del(cacheKey);
		returnJedis();
	}

	public static void increment(String cacheKey){
		Jedis jedis = getJedis();
		jedis.incr(cacheKey);
		returnJedis();
	}

	public static void decrement(String cacheKey){
		Jedis jedis = getJedis();
		jedis.decr(cacheKey);
		returnJedis();
	}

	public static boolean contains(String cacheKey){
		Jedis jedis = getJedis();
		boolean result = jedis.exists(cacheKey);
		returnJedis();
		return result;
	}


	public static void init() {
		getJedis();
		jedis.flushAll();
		returnJedis();
	}
}
